package com.karry.yl.web.services;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.JsonResponse;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.baseinfo.Employee;
import com.karry.yl.domain.elder.CheckInRecords;
import com.karry.yl.domain.elder.Elderly;
import com.karry.yl.domain.healthdata.HealthData;
import com.karry.yl.domain.healthdata.HealthDataItem;
import com.karry.yl.domain.services.Items;
import com.karry.yl.domain.services.Meal;
import com.karry.yl.domain.services.MealItems;
import com.karry.yl.domain.services.Records;
import com.karry.yl.service.baseinfo.EmployeeService;
import com.karry.yl.service.elder.CheckInRecordsService;
import com.karry.yl.service.elder.ElderlyService;
import com.karry.yl.service.healthdata.HealthDataService;
import com.karry.yl.service.personnel.DepartmentService;
import com.karry.yl.service.services.ItemsService;
import com.karry.yl.service.services.MealItemsService;
import com.karry.yl.service.services.MealService;
import com.karry.yl.service.services.RecordsService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;


/**
 * 服务记录Controller
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/records")
public class RecordsController extends SuperController {

    @Autowired
    private ItemsService itemsService;
    @Autowired
    private RecordsService recordsService;
    @Autowired
    private ElderlyService elderlyService;
    @Autowired
    private HealthDataService healthDataService;
    @Autowired
    private CheckInRecordsService checkInRecordsService;
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping
    public String listUI() {
        return "services/records/list";
    }

    @RequestMapping("/add")
    public String addUI(Integer healthCondition, ModelMap map, HttpSession session) {
        Long id = currentUser.getId();
        Employee employee = employeeService.selectOne(new EntityWrapper<Employee>().eq("userId", id).eq("deleted", false).eq("status", 1));
        List<Items> items=new ArrayList<>();
        List<Elderly> elderlies=new ArrayList<>();
        if(employee==null){
            map.put("items", items);
            map.put("elderlies",elderlies);
            return "services/records/add";
        }

        Long departmentId = employee.getDepartmentId();
        items = itemsService.selectList(new EntityWrapper<Items>().eq("orgId", currentUser.getOrgId()).eq("deleted", false));
        map.put("items", items);
        if (healthCondition != null && healthCondition != 0) {
            elderlies = elderlyService.selectList(new EntityWrapper<Elderly>().eq("healthCondition", healthCondition).eq("orgId", currentUser.getOrgId()).eq("checkedIn", true).eq("deleted", false).eq("nursingDepartmentId",departmentId).eq("allocationStart",true));
        } else {
            elderlies = elderlyService.selectList(new EntityWrapper<Elderly>().eq("orgId", currentUser.getOrgId()).eq("checkedIn", true).eq("deleted", false).eq("nursingDepartmentId",departmentId).eq("allocationStart",true));
        }
        if (elderlies != null && elderlies.size() > 0) {
            for (Elderly elderly : elderlies) {
                CheckInRecords checkInRecords = checkInRecordsService.selectOne(new EntityWrapper<CheckInRecords>().eq("elderlyId", elderly.getId()).eq("orgId", currentUser.getOrgId()).eq("deleted", false));
                //楼号
                elderly.setBuildingNo(checkInRecords.getBuildingNo());
                //房间号
                elderly.setRoomNo(checkInRecords.getRoomNo());
                //床位号
                elderly.setBedNo(checkInRecords.getBedNo());
                //床位Id
                elderly.setBedId(checkInRecords.getBedId());
            }
        }
        session.removeAttribute("elderlyIdNo");
        map.put("elderlies", elderlies);
        return "services/records/add";
    }

    @RequestMapping("edit")
    public String editUI(Long id, ModelMap map) {
        List<Items> items = itemsService.selectList(new EntityWrapper<Items>().eq("orgId", currentUser.getOrgId()).eq("deleted", false));
        map.put("items", items);
        Records records = recordsService.selectOne(new EntityWrapper<Records>().eq("id", id).eq("orgId", currentUser.getOrgId()).eq("deleted", false));
        map.put("records", records);
        // 获取本次服务所填写的健康记录
        if (records.getType() == Records.TYPE_TJ) {
            List<HealthData> healthDataList = healthDataService.selectList(new EntityWrapper<HealthData>().eq("recordsId", records.getId()));
            map.put("healthDataList", healthDataList);
        }
        return "services/records/edit";
    }

    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(int page, int limit, String elderlyName, String elderlyCode) {
        Wrapper<Records> recordsWrapper = new EntityWrapper<Records>().eq("orgId", currentUser.getOrgId()).eq("deleted", false);
        if (!StringUtils.isEmpty(elderlyName)) {
            recordsWrapper.like("elderlyName", elderlyName);
        }
        if (!StringUtils.isEmpty(elderlyCode)) {
            recordsWrapper.like("elderlyCode", elderlyCode);
        }
        Page<Records> recordsPage = recordsService.selectPage(new Page<Records>(page, limit), recordsWrapper.orderBy("serviceDate", false));
        return new LayTableResponse(recordsPage.getRecords(), recordsPage.getTotal());
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public JsonResponse save(String records, String  healthDatas,HttpSession session) {

        try {
            String elderlyIdNo = (String) session.getAttribute("elderlyIdNo");
            Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("idNo", elderlyIdNo).eq("orgId", currentUser.getOrgId()).eq("deleted", false));
            recordsService.saveData(records,healthDatas, elderly,currentUser.getId(),currentUser.getUserName(),currentUser.getOrgId(),currOrganization.getName());
            return new JsonResponse(200, "成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new JsonResponse(0, "失败");
    }



    @RequestMapping("/update")
    public String update(Records records, Long[] healthDataItemId, String[] healthDataitemName, String[] value, Boolean[] nature, String[] description, String[] standardValues) {
        Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("code", records.getElderlyCode()).eq("orgId", currentUser.getOrgId()).eq("deleted", false));
        if (null != elderly) {
            records.setUserId(currentUser.getId());
            records.setUserName(currentUser.getUserName());
            records.setElderlyId(elderly.getId());
            records.setElderlyName(elderly.getName());
            records.setOrgId(currentUser.getOrgId());
            Items items = itemsService.selectById(records.getItemId());

            //健康数据
            List<HealthData> healthDataList = new ArrayList<>();
            if (records.getType() == Records.TYPE_TJ) {
                for (int i = 0; i < healthDataItemId.length; i++) {
                    HealthData healthData = new HealthData(elderly.getId(), healthDataItemId[i], healthDataitemName[i], value[i], nature[i], description[i], standardValues[i]);
                    healthDataList.add(healthData);
                }
            }
            recordsService.update(records, healthDataList);
        }
        return "redirect:/records";
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @RequestMapping(path = "/delete")
    public String delete(@RequestParam("id") List<Long> ids) {
        recordsService.deleteBatchIds(ids);
        return "redirect:/records";
    }

    @RequestMapping(path = "/exists")
    @ResponseBody
    public JsonResponse elderlyExists(String elderlyCode) {

        Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("code", elderlyCode).eq("orgId", currentUser.getOrgId()).eq("deleted", false));
        if (null != elderly) {
            return JsonResponse.success(true);
        }
        return JsonResponse.success(false);
    }

    @RequestMapping(path = "/elderlyinfo")
    @ResponseBody
    public JsonResponse elderlyinfo(String elderlyCode) {

        Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("code", elderlyCode).eq("orgId", currentUser.getOrgId()).eq("deleted", false));
        if (null != elderly) {
            return JsonResponse.success(elderly);
        }
        return JsonResponse.success(false);
    }

    /**
     * 获取某个服务项目所能产生的数据项目
     *
     * @param serviceItemId 服务项目ID
     * @return
     */
    @RequestMapping("/healthDataItems")
    @ResponseBody
    public JsonResponse healthDataItems(Long serviceItemId) {
        List<HealthDataItem> healthDataItemList = itemsService.getHealthDataItemsByServiceItemId(serviceItemId);
        return JsonResponse.success(healthDataItemList);
    }


    /**
     * 服务记录档案导出为excel
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) {
        //查询所有的巡检记录
        List<Records> records = recordsService.selectList(new EntityWrapper<Records>().eq("orgId", currentUser.getOrgId()));
        //生成Excel,并存储临时文件
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("服务记录");

        // 表头
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        String[] title = {"所属老人", "项目名称", "费用", "备注", "服务时间"};
        for (int i = 0; i < title.length; i++) {
            row.setHeightInPoints(20);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 21 * 256);
        }

        //创建内容
        for (int i = 0; i < records.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(20);
            Records records1 = records.get(i);
            row.createCell(0).setCellValue(records1.getElderlyName());
            row.createCell(1).setCellValue(records1.getItemName());
            row.createCell(2).setCellValue(records1.getCost().longValue());
            row.createCell(3).setCellValue(records1.getRemark());
            String format = TimeUtil.format(records1.getServiceDate(), "yyyy-MM-dd");
            row.createCell(4).setCellValue(format);
        }

        //下载
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("服务记录-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls", "UTF-8"));
            wb.write(out);
        } catch (IOException e) {
            //TODO 下载失败日志记录
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Autowired
    private MealService mealService;

    @Autowired
    private MealItemsService mealItemsService;


    /**
     * 选择项目页面
     *
     * @return
     */
    @RequestMapping("/find/items")
    public String findItemUI(Long id, ModelMap map, HttpSession session) {
        Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("id", id).eq("orgId", currentUser.getOrgId()).eq("checkedIn", true).eq("deleted", false));
        //老人绑定了护理级别
        //根据当前的老人id选择绑定的护理级别'
        Meal meal = mealService.selectById(elderly.getMealId());
        //查询出所有的属于该护理级别的护理项目
        List<MealItems> mealItemsList = mealItemsService.selectList(new EntityWrapper<MealItems>().eq("mealId", meal.getId()));
        List<Items> items = new ArrayList<>();
        for (MealItems mealItems : mealItemsList) {
            items.add(itemsService.selectById(mealItems.getItemsId()));
        }
        map.put("items", items);
        session.setAttribute("elderlyIdNo", elderly.getIdNo());
        return "services/records/mealItems";
    }

}
